package Stream;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author Mr.Wen
 * @Version 1.0
 */
public class TestStreamAPI2 {
    @Test
    void test1() {
        List<Employee> employees = EmployeeData.getEmployees();
//        allMatch检查是否匹配所有元素
        System.out.println(employees.stream().allMatch((employee -> employee.getAge() > 18)));
//        anyMatch检查是否至少匹配一个元素
        System.out.println();
        System.out.println("employees.stream().anyMatch((employee -> employee.getAge() > 26)):\t" + employees.stream().anyMatch((employee -> employee.getAge() > 26)));
//        findFirst返回第一个元素
        System.out.println();
        System.out.println("employees.stream().findFirst():\t" + employees.stream().findFirst());
    }

    @Test
    void test2() {/*max min*/
        List<Employee> employees = EmployeeData.getEmployees();
//        返回满足的个数
        System.out.println(employees.stream().filter(employee -> employee.getAge() > 18).count());
//        返回最高工资的员工
        System.out.println(employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
//        返回最高工资
        System.out.println(employees.stream().map(emp -> emp.getSalary()).max(Double::compare));
//        最低工资的员工
        System.out.println();
        System.out.println(employees.stream().min((a, b) -> Double.compare(a.getSalary(), b.getSalary())));
    }

    @Test
    void test3() {/*reduce*/
        List<Employee> employees = EmployeeData.getEmployees();
        /*reduce 可以将流中的元素反复结合起来,得到一个值,返回T*/
        List<Integer> list = Arrays.asList(1, 3, 5, 7, 9);
        System.out.println(list.stream().reduce(0, Integer::sum));/*第一个参数相当于种子,基数*/
        System.out.println(list.stream().reduce(10, (x1, x2) -> x1 + x2));
        /*所有员工的工资总和*/
        System.out.println();
        System.out.println(employees.stream().map(emp -> emp.getSalary()).reduce((x1, x2) -> Double.sum(x1, x2)));
    }

    @Test/*收集collect(Collector c)*/
    void test4() {
//        将流中的数据保存下来,通过Collector的实现方法接收返回值类型
        List<Employee> employees = EmployeeData.getEmployees();
        List<Double> collect = employees.stream().filter(employee -> employee.getSalary() > 6000).map(emp -> emp.getSalary()).collect(Collectors.toList());
        collect.forEach(System.out::println);
//        按照员工年龄排序放到list集合
        System.out.println();
        List<Employee> collect1 = employees.stream().sorted((x1, x2) -> Integer.compare(x1.getAge(), x2.getAge())).collect(Collectors.toList());
        collect1.forEach(System.out::println);
    }


}
